// pages/my/setting/index.js
const AJAX = require("../../../common/request")
const API = require("../../../common/api")
const common = require("../../../common/common")
const App = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navTop: 0,
    navContentHeight: 0,
    placeholderHeight: 0,
    tabsId: 0,
    tabs: [{
        title: "常见病普及"
      },
      {
        title: "药品"
      },
    ],
    page: 1,
    rows: [],
    UPLOADURL: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    this.setData({
      navTop: App.globalData.navTop,
      navContentHeight: App.globalData.navContentHeight,
      options: JSON.stringify(options),
      UPLOADURL: API.UPLOADURL,
    })
    const query = wx.createSelectorQuery();
    query.select('.head').boundingClientRect();
    query.exec((res) => {
      this.setData({
        placeholderHeight: res[0].height
      })
    });
    await common.checkLogin()
    this.getList()
  },
  getList() {
    let url = ''
    if (this.data.tabsId == 0) {
      url = '/system/AppWechat/getMyClumn'
    } else {
      url = '/system/AppWechat/getMyDug'
    }
    console.log(App.globalData.user.wechatUserId)
    AJAX.POST(url, {
      wechatUserId: App.globalData.user.wechatUserId,
      page: this.data.page,
    }).then((res) => {
      console.log(res)
      if (res.code == 200) {
        this.setData({
          rows: res.rows
        })
      }
    })
  },
  setTabs(e) {
    console.log(e)
    this.setData({
      tabsId: e.currentTarget.dataset.index
    })
    this.getList()
  },
  // 前往页面
  goPage(e) {
    let url = e.currentTarget.dataset.url
    let params = e.currentTarget.dataset.params
    console.log(params.id)

    let pageUrl = params ? `${url}?id=${params.id}` : url
    wx.navigateTo({
      url: pageUrl,
    })
  },
  //详情
  goDrugDetail(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/index/drug/detail/index?id=' + id,
    })
  },
  //取消收藏
  deleteBCollect(e) {
    let index = e.currentTarget.dataset.index
    let data = this.data.rows
    let id = data[index].id
    let param = {}
    param.wechatUserId = App.globalData.user.wechatUserId
    if (this.data.tabsId == 0) {
      param.columnArticleId = id
    } else {
      param.drugIntroductionId = id
    }
    //type3 取消收藏
    param.type = 3
    AJAX.POST('/system/AppWechat/deleteBCollectByRefid', param)
    data.splice(index, 1)
    this.setData({
      rows: data
    })

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log('sdfsdf')
  },
  goBack() {
    const pages = getCurrentPages();
    //获取不到上级返回首页
    if (pages.length > 1) {
      wx.navigateBack({})
    } else {
      wx.reLaunch({
        url: '/pages/index/index',
      })
    }
  },

  // 点赞
  clickLike(e) {

    let addOrDel = this.data.rows[e.currentTarget.dataset.index].dzNum > 0 ? 2 : 1
    // 检查登录状态
    common.checkLogin().then((loginRes) => {
      if (!loginRes) {
        return wx.showToast({
          title: '尚未登录，点赞失败',
          duration: "3000",
          icon: "none"
        })
      }
      AJAX.POST("/system/AppWechat/updateNumber", {
        id: e.currentTarget.dataset.id,
        wechatUserId: App.globalData.user.wechatUserId,
        type: 1, // 1点赞，2转发
        addOrDel: addOrDel,
      }).then(res => {
        wx.showToast({
          title: addOrDel == 1 ? '点赞完成' : "取消点赞",
        })
        let likeUmber = 0
        if (addOrDel == 1) {
          likeUmber = this.data.rows[e.currentTarget.dataset.index].likenUmber + 1
        } else {
          likeUmber = this.data.rows[e.currentTarget.dataset.index].likenUmber - 1
          likeUmber = likeUmber > 0 ? likeUmber : 0
        }
        this.setData({
          [`rows[${e.currentTarget.dataset.index}].dzNum`]: addOrDel == 1 ? 1 : 0,
          [`rows[${e.currentTarget.dataset.index}].likenUmber`]: likeUmber,
        })
      })
    })
  },
  // 收藏
  clickCollect(e) {
    // 检查登录状态
    common.checkLogin().then((loginRes) => {
      if (!loginRes) {
        return wx.showToast({
          title: '尚未登录，收藏失败',
          duration: "3000",
          icon: "none"
        })
      }
      AJAX.POST("/system/AppWechat/addbCollect", {
        wechatUserId: App.globalData.user.wechatUserId,
        columnArticleId: e.currentTarget.dataset.id
      }).then(res => {
        wx.showToast({
          title: '文章收藏成功',
        })
      })
    })
  },
  onShareAppMessage(options) {
    // 如果该参数存在，则以 resolve 结果为准，如果三秒内不 resolve，分享会使用上面传入的默认参数
    const promise = new Promise(resolve => {
      // 页面按钮点击分享触发
      if (options.from === "button") {
        let params = options.target.dataset.params
        let sharetype = options.target.dataset.sharetype
        // 分享业务类型
        switch (sharetype) {
          // 指定常见病分享配置 sharetype=article_share
          case "article_share":
            resolve({
              title: params.columnArticleTitle || "分享至好友",
              // shareparams 分享链接，由链接进入小程序页面时需要使用的参数值
              path: `/pages/index/article/detail/index?id=${params.id}`,
              imageUrl: ""
            })
            AJAX.POST("/system/AppWechat/updateNumber", {
              id: params.id,
              wechatUserId: App.globalData.user.wechatUserId,
              type: 2 // 1点赞，2转发
            }).catch(err => {
              console.error("转发次数记录失败", err)
            })
            break;

          default:
            break;
        }

      }
    })

    // 默认分享配置
    return {
      title: App.globalData.onShareAppMessage.title,
      path: App.globalData.onShareAppMessage.path,
      imageUrl: App.globalData.onShareAppMessage.imageUrl,
      promise
    }
  },

})